import { useMutation, useQueryClient } from "@tanstack/react-query";
import { userAPI } from "@/api/user";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { useErrorHandler } from "@/lib/error-handler";
import type { ErrorResponse, Response } from "@/types/response";
import type { AxiosError } from "axios";

/**
 * 发送手机号更新验证码 hooks
 */
export const useSendMobileUpdateCaptcha = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();

  const sendMobileUpdateCaptchaMutation = useMutation({
    mutationFn: userAPI.sendMobileUpdateCaptcha,
    onSuccess: (response: Response) => {
      if (response.code === 200) {
        toast.success(t("Verification code sent"), {
          description:
            response.message ||
            t(
              "A verification code has been sent to your mobile. Please check your messages.",
              {
                defaultValue:
                  "A verification code has been sent to your mobile. Please check your messages.",
              }
            ),
          duration: 5000,
        });
      } else {
        toast.error(t("Failed to send verification code"), {
          description:
            response.message ||
            t(
              "An error occurred while sending verification code. Please try again."
            ),
          duration: 5000,
        });
      }
    },
    onError: (error: AxiosError<ErrorResponse, unknown>) => {
      const errorResult = errorHandler.handleApiError(error);

      if (errorResult.type === "warning") {
        toast.warning(t("Failed to send verification code"), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Failed to send verification code"), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      console.error("Send mobile update captcha error:", error);
    },
  });

  return {
    sendMobileUpdateCaptcha: sendMobileUpdateCaptchaMutation.mutate,
    sendMobileUpdateCaptchaAsync: sendMobileUpdateCaptchaMutation.mutateAsync,
    isSendingCaptcha: sendMobileUpdateCaptchaMutation.isPending,
    sendCaptchaError: sendMobileUpdateCaptchaMutation.error,
  };
};

/**
 * 更新手机号 hooks
 */
export const useUpdateMobile = () => {
  const { t } = useTranslation();
  const errorHandler = useErrorHandler();
  const queryClient = useQueryClient();

  const updateMobileMutation = useMutation({
    mutationFn: userAPI.updateMobile,
    onSuccess: (response: Response) => {
      if (response.code === 200) {
        // 使缓存失效，重新获取用户信息
        queryClient.invalidateQueries({ queryKey: ["user"] });
        toast.success(
          t("Mobile updated successfully", {
            defaultValue: "Mobile updated successfully",
          }),
          {
            description:
              response.message ||
              t("Your mobile number has been updated successfully.", {
                defaultValue: "Your mobile number has been updated successfully.",
              }),
            duration: 5000,
          }
        );
      } else {
        toast.error(t("Mobile update failed"), {
          description:
            response.message ||
            t("An error occurred during mobile update. Please try again."),
          duration: 5000,
        });
      }
    },
    onError: (error: AxiosError<ErrorResponse, unknown>) => {
      const errorResult = errorHandler.handleApiError(error);

      if (errorResult.type === "warning") {
        toast.warning(t("Mobile update failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      } else {
        toast.error(t("Mobile update failed"), {
          description: errorResult.message,
          duration: 5000,
        });
      }
      console.error("Update mobile error:", error);
    },
  });

  return {
    updateMobile: updateMobileMutation.mutate,
    updateMobileAsync: updateMobileMutation.mutateAsync,
    isUpdatingMobile: updateMobileMutation.isPending,
    updateMobileError: updateMobileMutation.error,
  };
};
